package cn.lili.modules.grab.xdxt.facade;

import cn.lili.common.event.TransactionCommitSendMQEvent;
import cn.lili.common.utils.CurrencyUtil;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.utils.UuidUtils;
import cn.lili.exchange.AmqpExchangeProperties;
import cn.lili.modules.goods.entity.dos.Goods;
import cn.lili.modules.goods.entity.dos.GoodsGallery;
import cn.lili.modules.goods.entity.dos.GoodsSku;
import cn.lili.modules.goods.entity.dos.StoreGoodsLabel;
import cn.lili.modules.goods.entity.enums.GoodsAuthEnum;
import cn.lili.modules.goods.service.GoodsGalleryService;
import cn.lili.modules.goods.service.GoodsService;
import cn.lili.modules.goods.service.GoodsSkuService;
import cn.lili.modules.goods.service.StoreGoodsLabelService;
import cn.lili.modules.grab.dingdong.reps.goods.DetailRespose;
import cn.lili.modules.grab.enums.SourceEnums;
import cn.lili.modules.grab.xdxt.reps.goods.GoodsCateReps;
import cn.lili.modules.grab.xdxt.reps.goods.ListGoodsReps;
import cn.lili.routing.GoodsRoutingKey;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class GrabXdxtGoodsFacade {

    @Resource
    private StoreGoodsLabelService storeGoodsLabelService;
    @Resource
    private GoodsService goodsService;
    @Resource
    private GoodsSkuService goodsSkuService;
    @Resource
    private GoodsGalleryService goodsGalleryService;
    @Resource
    private AmqpExchangeProperties amqpExchangeProperties;
    @Resource
    private ApplicationEventPublisher applicationEventPublisher;

    /**
     * 递归分类
     *
     * @param storeId       门店ID
     * @param goodsCateReps 所有分类
     * @param supId         分类ID
     * @param leven         当前等级
     */
    public void recursionCategory(String storeId, GoodsCateReps goodsCateReps, int supId, int leven) {
        List<GoodsCateReps.Category> collect = goodsCateReps.getResult().stream().filter(e -> supId == e.getSupId()).toList();
        if (collect.isEmpty()) {
            return;
        }
        leven = leven + 1;
        for (GoodsCateReps.Category category : collect) {
            //新增或修改分类
            storeGoodsLabelInit(storeId, category, leven);
            //递归查询
            recursionCategory(storeId, goodsCateReps, category.getId(), leven);
        }
    }


    /**
     * 插入分类
     *
     * @param storeId  店铺ID
     * @param category 当前分类
     */
    public void storeGoodsLabelInit(String storeId, GoodsCateReps.Category category, int level) {
        //查询当前分类
        LambdaQueryWrapper<StoreGoodsLabel> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(StoreGoodsLabel::getStoreId, storeId);
        queryWrapper1.eq(StoreGoodsLabel::getSourceId, category.getId());
        queryWrapper1.last("limit 1");
        StoreGoodsLabel storeGoodsLabel1 = storeGoodsLabelService.getBaseMapper().selectOne(queryWrapper1);

        //查询parentId是否存在
        LambdaQueryWrapper<StoreGoodsLabel> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(StoreGoodsLabel::getStoreId, storeId);
        queryWrapper2.eq(StoreGoodsLabel::getSourceId, category.getSupId());
        queryWrapper2.last("limit 1");
        StoreGoodsLabel storeGoodsLabel2 = storeGoodsLabelService.getBaseMapper().selectOne(queryWrapper2);

        //更新或新增分类
        if (storeGoodsLabel1 != null) {
            //修改更新
            storeGoodsLabel1.setStoreId(storeId);
            storeGoodsLabel1.setLabelName(category.getName());
            storeGoodsLabel1.setSortOrder(BigDecimal.valueOf(0));
            storeGoodsLabel1.setParentId(storeGoodsLabel2 != null ? storeGoodsLabel2.getId() : "0");
            storeGoodsLabel1.setLevel(level);
            storeGoodsLabel1.setSource(SourceEnums.XDXT_GOODS.name());
            storeGoodsLabel1.setSourceId(String.valueOf(category.getId()));
            storeGoodsLabelService.editStoreGoodsLabel(storeGoodsLabel1);
        } else {
            //新增
            StoreGoodsLabel storeGoodsLabel = StoreGoodsLabel.builder()
                    .storeId(storeId)
                    .labelName(category.getName())
                    .sortOrder(BigDecimal.valueOf(0))
                    .parentId(storeGoodsLabel2 != null ? storeGoodsLabel2.getId() : "0")
                    .level(level)
                    .source(SourceEnums.XDXT_GOODS.name())
                    .sourceId(String.valueOf(category.getId()))
                    .build();
            storeGoodsLabelService.addStoreGoodsLabel(storeGoodsLabel);
        }
    }

    /**
     * 初始化商品并入库
     *
     * @param storeId 店铺ID
     * @param records 商品数据
     */
    public void goodsInit(String storeId, ListGoodsReps.Result.Records records) {
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Goods::getStoreId, storeId);
        queryWrapper.eq(Goods::getThirdPartyPlatformId, records.getId());
        queryWrapper.eq(Goods::getDeleteFlag,false);
        queryWrapper.last("limit 1");
        Goods tempGoods = goodsService.getBaseMapper().selectOne(queryWrapper);

        Goods goods = new Goods();
        goods.setGoodsName("S-" + records.getTitle());
        goods.setPrice(CurrencyUtil.mul(CurrencyUtil.convertDouble(records.getSpecificationList().get(0).getCurrVipPrice()), 1.05, 1));
        goods.setDefaultSkuGreenScore(new BigDecimal(CurrencyUtil.mul(CurrencyUtil.convertDouble(records.getSpecificationList().get(0).getCurrVipPrice()), 0.1, 0)));

        //查询分类
        StringBuffer cateStorePath = new StringBuffer();
        if(!records.getGoodsCategoryList().isEmpty()){
            String cate1 = getStoreGoodsLabel(String.valueOf(records.getGoodsCategoryList().get(0).getC1()));
            String cate2 = getStoreGoodsLabel(String.valueOf(records.getGoodsCategoryList().get(0).getC2()));
            String cate3 = getStoreGoodsLabel(String.valueOf(records.getGoodsCategoryList().get(0).getC3()));
            cateStorePath.append(cate1);
            cateStorePath.append(",");
            cateStorePath.append(cate2);
            cateStorePath.append(",");
            cateStorePath.append(cate3);
        }

        goods.setGoodsUnit("件");
        goods.setMarketEnable("DOWN");
        goods.setBuyCount(0);
        goods.setQuantity(records.getSpecificationList().get(0).getStockNum());
        goods.setThumbnail(records.getMainImg());
        goods.setSmall(records.getMainImg());
        goods.setOriginal(records.getMainImg());
        goods.setGoodsVideo(records.getSpecificationList().get(0).getVideo());
        goods.setStoreCategoryPath(cateStorePath.toString());
        goods.setStoreId(storeId);
        goods.setStoreName("供应");
        goods.setTemplateId("0");
        goods.setAuthFlag(GoodsAuthEnum.TOBEAUDITED.name());
        goods.setSelfOperated(true);
        goods.setRecommend(true);
        goods.setSalesModel("RETAIL");
        goods.setGoodsType("PHYSICAL_GOODS");
        goods.setIsGreenGoods(false);

        StringBuffer desc = new StringBuffer();
        for (String image:records.getSpecificationList().get(0).getDetailImgs()) {
            desc.append("<p><img src=\""+image+"\"></p>");

        }
        goods.setIntro(desc.toString());
        goods.setMobileIntro(desc.toString());
        goods.setScene("STORE");
        goods.setExtendId(storeId);
        goods.setThirdPartyPlatformId(String.valueOf(records.getId()));
        goods.setThirdPartyPlatformType(3);

        //插入商品
        if (tempGoods == null) {
            goods.setCategoryPath("1,1,1");
            goodsService.save(goods);
        } else {
            goods.setId(tempGoods.getId());
            BeanUtils.copyProperties(goods, tempGoods);
            goodsService.updateGoods(tempGoods);
        }

        //插入商品相册，删除后新增
        goodsGalleryService.removeByGoodsId(goods.getId());
        GoodsGallery goodsGallery = new GoodsGallery();
        goodsGallery.setGoodsId(goods.getId());
        goodsGallery.setIsDefault(0);
        goodsGallery.setOriginal(records.getMainImg());
        goodsGallery.setThumbnail(records.getMainImg());
        goodsGallery.setSmall(records.getMainImg());
        goodsGalleryService.save(goodsGallery);

        //插入sku
        goodsSkuInit(storeId, records, cateStorePath.toString(), goods.getId());

        // 发送删除es商品的信息
        List<String> goodIds = new ArrayList<>();
        goodIds.add(goods.getId());
        applicationEventPublisher.publishEvent(TransactionCommitSendMQEvent
                .builder()
                .source("商品删除")
                .exchange(amqpExchangeProperties.getGoods())
                .routingKey(GoodsRoutingKey.GOODS_DELETE)
                .message(goodIds)
                .build());
    }

    /**
     * 初始化商品SKU并入库
     *
     * @param storeId 店铺ID
     */
    public void goodsSkuInit(String storeId, ListGoodsReps.Result.Records records, String catePath, String goodsId) {
        for (ListGoodsReps.Result.Records.Specification specification : records.getSpecificationList()) {
            LambdaQueryWrapper<GoodsSku> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(GoodsSku::getStoreId, storeId);
            queryWrapper.eq(GoodsSku::getThirdPartyPlatformId, specification.getCode());
            queryWrapper.eq(GoodsSku::getDeleteFlag,false);
            queryWrapper.last("limit 1");
            GoodsSku tempGoodsSku = goodsSkuService.getBaseMapper().selectOne(queryWrapper);

            GoodsSku goodsSku = new GoodsSku();
            goodsSku.setBig(specification.getItemMainImg());
            goodsSku.setSmall(specification.getItemMainImg());
            goodsSku.setBuyCount(0);
            goodsSku.setCommentNum(0);
            goodsSku.setGoodsId(goodsId);
            goodsSku.setGoodsName("S-" + records.getTitle());
            goodsSku.setStoreId(storeId);
            goodsSku.setStoreName("供应");
            goodsSku.setSn(UuidUtils.getUUID());

            JSONObject url = new JSONObject();
            url.put("url", specification.getItemMainImg());
            JSONArray images = new JSONArray();
            images.add(url);

            JSONObject specinfo = JSONObject.parseObject(specification.getSpecInfo());
            if(specinfo.size() < 1){
                specinfo.put("默认","默认");
            }

            JSONObject json = new JSONObject();
            json.put("images", images);

            specinfo.keySet().forEach(e-> {
                json.put(e,specinfo.getString(e));
            });

            goodsSku.setSimpleSpecs(specification.getSpecInfo());
            goodsSku.setSpecs(json.toJSONString());
            goodsSku.setGoodsType("PHYSICAL_GOODS");
            goodsSku.setIsGreenGoods(false);
            goodsSku.setQuantity(specification.getStockNum());
            goodsSku.setWeight(specification.getWeight());
            goodsSku.setCost(specification.getCurrVipPrice());
            goodsSku.setPrice(CurrencyUtil.mul(specification.getCurrVipPrice(), 1.05, 1));
            goodsSku.setGreenScore(CurrencyUtil.mul(goodsSku.getCost(), 0.1, 0));
            goodsSku.setIsProxyGoods(true);
            goodsSku.setScene("STORE");
            goodsSku.setFreightTemplateId("0");
            goodsSku.setGrade(100D);
            goodsSku.setMarketEnable("DOWN");
            goodsSku.setAuthFlag(GoodsAuthEnum.TOBEAUDITED.name());
            goodsSku.setRecommend(true);
            goodsSku.setSalesModel("RETAIL");
            goodsSku.setSelfOperated(false);
            goodsSku.setTemplateId("0");
            goodsSku.setOriginal(specification.getItemMainImg());
            goodsSku.setThumbnail(specification.getItemMainImg());
            goodsSku.setIsProxyGoods(false);
            goodsSku.setSupportProxy(true);
            goodsSku.setSupportPurchase(true);
            goodsSku.setThirdPartyPlatformId(specification.getCode());
            goodsSku.setThirdPartyPlatformType(3);
            goodsSku.setExtendId(storeId);
            goodsSku.setStoreCategoryPath(catePath);
            goodsSku.setGoodsUnit("件");

            StringBuffer desc = new StringBuffer();
            for (String image:specification.getDetailImgs()) {
                desc.append("<p><img src=\""+image+"\"></p>");

            }
            goodsSku.setIntro(desc.toString());
            goodsSku.setMobileIntro(desc.toString());

            //插入商品sku
            if (tempGoodsSku == null) {
                goodsSku.setCategoryPath("1,1,1");
                goodsSkuService.save(goodsSku);
            } else {
                goodsSku.setId(tempGoodsSku.getId());
                BeanUtils.copyProperties(goodsSku, tempGoodsSku);
                goodsSkuService.update(tempGoodsSku);
            }
        }
    }

    /**
     * 根据来源ID查询分类ID
     *
     * @param sourceId 来源ID
     */
    public String getStoreGoodsLabel(String sourceId) {
        if (StringUtils.isEmpty(sourceId)) {
            return null;
        }
        LambdaQueryWrapper<StoreGoodsLabel> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(StoreGoodsLabel::getSourceId, sourceId);
        queryWrapper1.last("limit 1");
        StoreGoodsLabel storeGoodsLabel = storeGoodsLabelService.getBaseMapper().selectOne(queryWrapper1);
        return storeGoodsLabel != null ? storeGoodsLabel.getId() : null;
    }
}
